// 数据可视化模块
// 使用Chart.js实现各种图表功能

// 初始化所有可视化图表
function initVisualizations() {
  try {
    // 初始化雷达图 - 情报源质量评估维度
    initRadarChart();
    
    // 初始化折线图 - 专题增长趋势
    if (typeof Chart !== 'undefined') {
      initLineChart();
    } else {
      console.warn('Chart.js未加载，跳过折线图初始化');
    }
    
    // 初始化饼图 - 情报类别分布
    if (typeof Chart !== 'undefined') {
      initPieChart();
    } else {
      console.warn('Chart.js未加载，跳过饼图初始化');
    }
    
    // 初始化进度条图表
    initProgressCharts();
    
    // 初始化时间轴可视化
    try {
      initTimelineChart();
    } catch (error) {
      console.warn('时间轴初始化失败，但不影响主要功能:', error);
    }
  } catch (error) {
    console.error('可视化初始化出错:', error);
    // 错误不应该阻止页面其余部分的功能
  }
}

// 初始化雷达图 - 用于展示情报源质量评估维度
function initRadarChart() {
  const ctx = document.getElementById('quality-radar-chart');
  if (!ctx) return;
  
  // 获取模拟数据
  const data = getQualityRadarData();
  
  // 安全检查：确保Chart对象存在
  if (typeof Chart === 'undefined' || typeof Chart !== 'function') {
    console.warn('Chart.js未正确加载，使用简单DOM渲染替代雷达图');
    // 使用简单的DOM元素替代图表
    const container = ctx.parentElement;
    container.innerHTML = `
      <div class="p-4 bg-gray-50 rounded-lg">
        <h4 class="font-medium mb-2">情报源质量评估维度</h4>
        <div class="space-y-2">
          ${data.datasets[0].data.map((value, index) => {
            const labels = ['及时性', '命中率', '差异性', '丰富性', '准确性'];
            const colors = ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899'];
            return `
              <div>
                <div class="flex justify-between text-sm mb-1">
                  <span>${labels[index]}</span>
                  <span>${value}%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                  <div class="h-2 rounded-full" style="background-color: ${colors[index]}; width: ${value}%"></div>
                </div>
              </div>
            `;
          }).join('')}
        </div>
      </div>
    `;
    return;
  }
  
  // 尝试创建图表
  try {
    new Chart(ctx, {
      type: 'radar',
      data: {
        labels: ['及时性', '命中率', '差异性', '丰富性', '准确性'],
        datasets: data.datasets
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          r: {
            beginAtZero: true,
            max: 100,
            ticks: {
              stepSize: 20,
              backdropColor: 'transparent',
              color: '#64748b'
            },
            pointLabels: {
              color: '#334155',
              font: {
                size: 12
              }
            },
            grid: {
              color: 'rgba(148, 163, 184, 0.2)'
            },
            angleLines: {
              color: 'rgba(148, 163, 184, 0.2)'
            }
          }
        },
        plugins: {
          legend: {
            position: 'bottom',
            labels: {
              padding: 20,
              usePointStyle: true,
              pointStyle: 'circle'
            }
          },
          tooltip: {
            backgroundColor: 'rgba(30, 41, 59, 0.9)',
            padding: 12,
            titleFont: {
              size: 14
            },
            bodyFont: {
              size: 13
            },
            displayColors: true,
            callbacks: {
              label: function(context) {
                return `${context.dataset.label}: ${context.raw}%`;
              }
            }
          }
        },
        interaction: {
          mode: 'index',
          intersect: false
        }
      }
    });
  } catch (error) {
    console.error('创建雷达图时出错:', error);
    // 降级到简单DOM渲染
    const container = ctx.parentElement;
    container.innerHTML = `<div class="p-4 bg-gray-50 rounded-lg text-center">图表加载失败，请刷新页面重试</div>`;
  }
}

// 初始化折线图 - 用于展示专题增长趋势
function initLineChart() {
  const ctx = document.getElementById('trend-line-chart');
  if (!ctx) return;
  
  // 获取模拟数据
  const data = getTrendLineData();
  
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: data.labels,
      datasets: data.datasets
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        x: {
          grid: {
            display: false
          },
          ticks: {
            color: '#64748b'
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(148, 163, 184, 0.2)'
          },
          ticks: {
            color: '#64748b',
            callback: function(value) {
              return value;
            }
          }
        }
      },
      plugins: {
        legend: {
          position: 'top',
          labels: {
            padding: 20,
            usePointStyle: true,
            pointStyle: 'circle'
          }
        },
        tooltip: {
          backgroundColor: 'rgba(30, 41, 59, 0.9)',
          padding: 12,
          titleFont: {
            size: 14
          },
          bodyFont: {
            size: 13
          },
          displayColors: true,
          mode: 'index',
          intersect: false
        }
      },
      interaction: {
        mode: 'index',
        intersect: false
      },
      elements: {
        line: {
          tension: 0.3,
          borderWidth: 2
        },
        point: {
          radius: 3,
          hoverRadius: 5,
          hitRadius: 10
        }
      }
    }
  });
}

// 初始化饼图 - 用于展示情报类别分布
function initPieChart() {
  const ctx = document.getElementById('category-pie-chart');
  if (!ctx) return;
  
  // 获取模拟数据
  const data = getCategoryPieData();
  
  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: data.labels,
      datasets: data.datasets
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'right',
          labels: {
            padding: 20,
            usePointStyle: true,
            pointStyle: 'circle'
          }
        },
        tooltip: {
          backgroundColor: 'rgba(30, 41, 59, 0.9)',
          padding: 12,
          titleFont: {
            size: 14
          },
          bodyFont: {
            size: 13
          },
          displayColors: true,
          callbacks: {
            label: function(context) {
              const total = context.dataset.data.reduce((acc, val) => acc + val, 0);
              const percentage = Math.round((context.raw / total) * 100);
              return `${context.label}: ${context.raw} (${percentage}%)`;
            }
          }
        }
      },
      cutout: '70%',
      animation: {
        animateScale: true,
        animateRotate: true
      }
    }
  });
}

// 初始化进度条图表
function initProgressCharts() {
  const progressBars = document.querySelectorAll('.progress-bar-container');
  progressBars.forEach(container => {
    const progress = container.querySelector('.progress-bar');
    const percentage = parseInt(container.dataset.percentage) || 0;
    
    // 动画效果
    let width = 0;
    const interval = setInterval(() => {
      if (width >= percentage) {
        clearInterval(interval);
      } else {
        width += 1;
        progress.style.width = width + '%';
      }
    }, 10);
    
    // 添加数值显示
    const value = document.createElement('span');
    value.className = 'text-xs font-medium text-gray-600 ml-2';
    value.textContent = percentage + '%';
    container.appendChild(value);
  });
}

// 初始化时间轴可视化
function initTimelineChart() {
  const timelineContainer = document.querySelector('.timeline-container');
  if (!timelineContainer) return;
  
  // 获取时间轴数据
  const timelineData = getTimelineData();
  
  // 渲染时间轴
  timelineContainer.innerHTML = '';
  timelineData.forEach((item, index) => {
    const isEven = index % 2 === 0;
    
    const timelineItem = document.createElement('div');
    timelineItem.className = `relative flex items-center mb-8 ${isEven ? 'flex-row' : 'flex-row-reverse'}`;
    
    // 时间点
    const point = document.createElement('div');
    point.className = `z-10 w-4 h-4 rounded-full bg-blue-500 ${isEven ? 'mr-4' : 'ml-4'}`;
    
    // 内容
    const content = document.createElement('div');
    content.className = `bg-white p-4 rounded-lg shadow-sm border border-gray-100 w-64 ${isEven ? 'text-left' : 'text-right'}`;
    
    const title = document.createElement('h4');
    title.className = 'font-medium text-gray-800';
    title.textContent = item.title;
    
    const time = document.createElement('p');
    time.className = 'text-xs text-gray-500 mt-1';
    time.textContent = item.time;
    
    const description = document.createElement('p');
    description.className = 'text-sm text-gray-600 mt-2';
    description.textContent = item.description;
    
    content.appendChild(title);
    content.appendChild(time);
    content.appendChild(description);
    
    timelineItem.appendChild(point);
    timelineItem.appendChild(content);
    
    timelineContainer.appendChild(timelineItem);
  });
  
  // 添加连接线
  const line = document.createElement('div');
  line.className = 'absolute left-2 top-0 bottom-0 w-0.5 bg-blue-100 z-0';
  timelineContainer.appendChild(line);
}

// 获取雷达图数据
function getQualityRadarData() {
  return {
    datasets: [
      {
        label: '当前配置',
        data: [85, 78, 90, 82, 75],
        backgroundColor: 'rgba(59, 130, 246, 0.2)',
        borderColor: 'rgba(59, 130, 246, 0.8)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(59, 130, 246, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(59, 130, 246, 1)'
      },
      {
        label: '历史平均',
        data: [70, 72, 65, 68, 75],
        backgroundColor: 'rgba(167, 139, 250, 0.2)',
        borderColor: 'rgba(167, 139, 250, 0.8)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(167, 139, 250, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(167, 139, 250, 1)'
      }
    ]
  };
}

// 获取折线图数据
function getTrendLineData() {
  return {
    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
    datasets: [
      {
        label: 'APT组织活动',
        data: [65, 59, 80, 81, 56, 92],
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        borderColor: 'rgba(59, 130, 246, 1)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(59, 130, 246, 1)',
        pointBorderColor: '#fff',
        fill: true
      },
      {
        label: '勒索软件',
        data: [28, 48, 40, 19, 86, 27],
        backgroundColor: 'rgba(239, 68, 68, 0.1)',
        borderColor: 'rgba(239, 68, 68, 1)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(239, 68, 68, 1)',
        pointBorderColor: '#fff',
        fill: true
      },
      {
        label: '钓鱼攻击',
        data: [35, 25, 30, 40, 35, 45],
        backgroundColor: 'rgba(245, 158, 11, 0.1)',
        borderColor: 'rgba(245, 158, 11, 1)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(245, 158, 11, 1)',
        pointBorderColor: '#fff',
        fill: true
      }
    ]
  };
}

// 获取饼图数据
function getCategoryPieData() {
  return {
    labels: ['APT活动', '勒索软件', '钓鱼攻击', '数据泄露', '漏洞信息', '其他'],
    datasets: [
      {
        data: [25, 20, 18, 15, 12, 10],
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(239, 68, 68, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(167, 139, 250, 0.8)',
          'rgba(16, 185, 129, 0.8)',
          'rgba(148, 163, 184, 0.8)'
        ],
        borderColor: [
          'rgba(59, 130, 246, 1)',
          'rgba(239, 68, 68, 1)',
          'rgba(245, 158, 11, 1)',
          'rgba(167, 139, 250, 1)',
          'rgba(16, 185, 129, 1)',
          'rgba(148, 163, 184, 1)'
        ],
        borderWidth: 1
      }
    ]
  };
}

// 获取时间轴数据
function getTimelineData() {
  return [
    {
      title: '新的APT组织活动发现',
      time: '2023-06-15 10:23',
      description: '发现针对能源行业的新型APT组织活动，使用鱼叉式钓鱼邮件'
    },
    {
      title: '高危漏洞CVE-2023-XXXX发布',
      time: '2023-06-12 08:45',
      description: '影响多个流行Web应用的远程代码执行漏洞，CVSS评分9.8'
    },
    {
      title: '勒索软件组织更新加密算法',
      time: '2023-06-08 15:32',
      description: 'BlackCat组织升级加密算法，增强了其加密强度和隐蔽性'
    },
    {
      title: '大规模数据泄露事件',
      time: '2023-06-01 14:10',
      description: '某社交平台发生数据泄露，影响超过1000万用户数据'
    },
    {
      title: '新型钓鱼攻击技术出现',
      time: '2023-05-28 09:55',
      description: '发现使用AI生成深度伪造视频的新型钓鱼攻击手法'
    }
  ];
}

// 在index.html加载完成后初始化可视化组件
document.addEventListener('DOMContentLoaded', function() {
  // 等待页面渲染完成后再初始化图表
  setTimeout(initVisualizations, 500);
});